<template>
  <div class="" style="padding: 1rem">
    <div style="display: flex; align-items: center">
      <a-image width="40" src="/logo.png" />
      <h3 style="margin-left: 10px">服务项目管理</h3>
    </div>

    <div style="margin-top: 10px">
      <div style="display: flex">
        <div>
          <a-input-search
            v-model="fuzzySearchValue"
            :style="{ width: '15vw' }"
            placeholder="请输入服务项目名称"
            :allow-clear="true"
            @search="fuzzySearchFc"
            @clear="fuzzySearchClearFc"
          />
        </div>
        <div style="margin-left: auto; display: flex; align-items: center;">
          <a-button style="margin-right: 8px" @click="showTemplateUpload = true">
            <template #icon>
              <IconUpload />
            </template>
            会务模板上传
          </a-button>
          <a-button type="primary" @click="update(1)">
            <template #icon>
              <icon-plus />
            </template>
            新增
          </a-button>
        </div>
      </div>
      <div style="margin-top: 10px; overflow-y: auto; height: 60vh">
        <a-table :columns="columns" :data="data" :pagination="false">
          <template #optional="{ record }">
            <a-button type="text" @click="update(2, record)">修改</a-button>
            <a-popconfirm content="你确定要删除吗?" @ok="datele(record.id)">
              <a-button type="text" status="danger">删除</a-button>
            </a-popconfirm>
          </template>
        </a-table>
      </div>
      <div style="margin-left: auto; display: flex; justify-content: flex-end">
        <!-- 添加分页器 -->
        <a-pagination
          v-model:current="page.current"
          v-model:page-size="page.pageSize"
          :total="page.total"
          :show-total="page.showTotal"
          :show-jumper="page.showJumper"
          :page-size-options="[5, 10, 20, 50]"
          :show-page-size="true"
          style="margin-top: 16px"
          @change="handlePageChange"
          @page-size-change="handlePageSizeChange"
        />
      </div>
    </div>

    <a-modal v-model:visible="visible" @ok="handleOk" @cancel="handleCancel">
      <template #title> {{ popupTitle }} </template>
      <div>
        <a-form ref="formRef" :rules="rules" :model="form">
          <a-form-item field="factoryId" label="厂区:">
            <a-select
              v-model="form.factoryId"
              placeholder="请选择厂区"
              @change="selectChange"
            >
              <!-- 动态渲染选项 -->
              <a-option
                v-for="item in options"
                :key="item.value"
                :value="item.value"
                :label="item.label"
              >
              </a-option>
            </a-select>
          </a-form-item>

          <a-form-item field="serviceCate" label="服务类:">
            <a-input
              v-model="form.serviceCate"
              placeholder="请输入"
              allow-clear
            />
          </a-form-item>
          <a-form-item field="serviceInfo" label="服务内容:">
            <a-input
              v-model="form.serviceInfo"
              placeholder="请输入"
              allow-clear
            />
          </a-form-item>
          <!-- 新增负责人字段 -->
          <a-form-item field="userName" label="负责人:" :rules="[{ required: true, message: '请选择负责人' }]">
            <div style="display: flex; align-items: center;">
              <a-button type="primary" @click="showUserModal = true">选择负责人</a-button>
              <div v-if="form.userName" style="margin-left: 12px; display: flex; align-items: center;">
                <img v-if="form.principalAvatar" :src="form.principalAvatar" style="width: 24px; height: 24px; border-radius: 50%; margin-right: 6px;" />
                <span>{{ form.userName }}</span>
                <span style="color: #f53f3f; margin-left: 8px; cursor: pointer;" @click="removeUserSelect">✖</span>
              </div>
            </div>
          </a-form-item>
        </a-form>
      </div>
      <!-- 负责人选择弹窗 -->
      <a-modal v-model:visible="showUserModal" title="选择负责人" :width="400" :height="500" @ok="handleUserConfirm">
        <div class="invite-modal-content">
          <a-input-search
            v-model="userSearchKeyword"
            placeholder="搜索部门或用户"
            class="search-input"
            :loading="userSearching"
            @input="handleUserSearch"
          />
          <a-tree
            v-model:selected-keys="selectedUserKeys"
            :data="isUserSearching ? userSearchResults : userTreeData"
            :multiple="false"
            @select="onUserNodeSelect"
          >
            <template #icon="{ node }">
              <span v-if="node.type === 'user'" class="custom-radio">
                <input
                  type="radio"
                  :checked="selectedUserKeys[0] === node.key"
                  style="margin-right: 6px; vertical-align: middle;"
                  @change="onUserRadioChange(node.key)"
                />
              </span>
            </template>
          </a-tree>
        </div>
      </a-modal>
    </a-modal>
    <a-modal v-model:visible="showTemplateUpload" title="会务模板上传" :footer="false" @cancel="handleTemplateUploadCancel">
      <div style="padding: 24px 8px 8px 8px; min-width: 320px;">
        <div class="upload-tips" style="background: #f7f8fa; padding: 12px 16px; border-radius: 6px; margin-bottom: 18px;">
          <ul style="margin: 0; padding-left: 18px; color: #86909c; font-size: 13px;">
            <li>支持的文件格式：Excel文件（.xlsx, .xls）</li>
            <li>文件大小不超过10MB</li>
            <li>请确保模板文件格式正确</li>
          </ul>
        </div>
        <a-upload
          v-model:file-list="templateFileList"
          :custom-request="handleTemplateUpload"
          :show-file-list="false"
          accept=".xlsx,.xls"
        >
          <a-button type="primary" style="width: 120px;">选择文件</a-button>
          <span v-if="templateFileList.length" style="margin-left: 12px; color: #1d2129;">{{ templateFileList[0].name }}</span>
        </a-upload>
        <div style="margin-top: 20px; text-align: right;">
          <a-button style="margin-right: 12px;" @click="handleTemplateUploadCancel">取消</a-button>
          <a-button type="primary" :loading="templateUploading" :disabled="!templateFileList.length" @click="submitTemplateUpload">上传</a-button>
        </div>
        <div v-if="recentTemplateUploads.length" style="margin-top: 24px; background: #f7f8fa; border-radius: 6px; padding: 12px 16px;">
          <h5 style="margin-bottom: 8px; color: #1d2129; font-size: 14px;">最近上传记录：</h5>
          <div style="display: flex; flex-direction: column; gap: 8px;">
            <div v-for="(item, idx) in recentTemplateUploads" :key="idx" style="display: flex; align-items: center; gap: 12px; font-size: 13px;">
              <span style="color: #1d2129;">{{ item.name }}</span>
              <span style="color: #86909c; flex: 1;">{{ item.time }}</span>
              <span :style="{ color: item.status === 'success' ? '#00b42a' : '#f53f3f', fontWeight: 500 }">
                {{ item.status === 'success' ? '成功' : '失败' }}
              </span>
            </div>
          </div>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts"
>
import { onMounted, reactive, ref } from 'vue'
import { Message } from '@arco-design/web-vue'
import { debounce } from 'lodash-es'
import { IconUpload } from '@arco-design/web-vue/es/icon'
import {
  addservice,
  deleteServiceDetail,
  factory,
  fuzzySearch,
  getgetserviceDetail,
  serviceItem,
  updateServiceDetail
} from '@/apis/meet/component'
import { getUserTree, searchTree } from '@/apis/startApp/meeting'
import { uploadTemplate } from '@/apis/meet/template'

const visible = ref(false)
// arco.design分页器参数
const page = reactive({
  current: 1, // 当前页码
  pageSize: 10, // 每页数量
  total: 0, // 总数据量（从接口获取）
  showTotal: true, // 是否显示总数
  showJumper: true // 是否显示页码跳转
})
const fuzzySearchValue = ref() // 搜索框模糊搜索的值
const formRef = ref() // 增加这行
const options = ref() // 厂区选择框数据列表
const serviceItemId = ref() // 服务项目对象id
const popupTitle = ref() // 弹窗组件标题

// 查询会议列表的参数
const form = ref<any>({
  factoryName: '',
  factoryId: '',
  serviceCate: '',
  serviceInfo: '',
  userId: '', // 新增负责人字段
  userName: '', // 新增负责人字段
  principal: '', // 新增负责人字段
  principalName: '', // 新增负责人字段
  principalAvatar: '' // 新增负责人字段
})

// const rules = {
//   factoryId: [
//     {
//       required: true,
//       message: "厂区不能为空",
//       validator: (value) => !!value?.trim(), // 额外空白字符校验
//     },
//   ],
//   serviceCate: [
//     {
//       required: true,
//       message: "服务类不能为空",
//     },
//   ],
//   serviceInfo: [
//     {
//       required: true,
//       message: "服务内容不能为空",
//     },
//   ],
// };
const columns = [
  {
    title: '厂区名称',
    dataIndex: 'factoryName'
  },
  {
    title: '服务项',
    slotName: 'serviceCate',
    dataIndex: 'serviceCate'
  },
  {
    title: '服务内容',
    slotName: 'serviceInfo',
    dataIndex: 'serviceInfo'
  },
  // 新增负责人列
  {
    title: '负责人',
    dataIndex: 'userName'
  },
  {
    title: '创建时间',
    dataIndex: 'createTime'
  },
  {
    title: '修改时间',
    dataIndex: 'updateTime'
  },
  {
    title: '操作',
    slotName: 'optional'
  }
]
const data = ref([]) // 表格数据

const handleClick = () => {
  visible.value = true
}
/**
 * 弹出框确认事件
 */
const handleOk = async () => {
  // 新增/修改接口调用时只传 userId 和 userName
  const submitData = {
    // 只传 userId 和 userName 以及其它业务字段，不传 principal/principalName
    ...form.value,
    userId: form.value.userId,
    userName: form.value.userName
  }
  // 移除 principal/principalName 字段
  delete submitData.principal
  delete submitData.principalName
  let res
  if (popupTitle.value === '新增') {
    res = await addservice(submitData)
    if (res && res.success !== false) {
      Message.success('添加成功')
    }
    getServiceItemFc()
  } else {
    // 修改
    res = await updateServiceDetail(submitData, serviceItemId.value)
    if (res && res.success === true) {
      Message.success('修改成功')
      getServiceItemFc()
    } else {
      Message.success('修改失败')
    }
  }

  visible.value = false
}

/**
 * 弹窗取消事件
 */
const handleCancel = () => {
  visible.value = false
  form.value = {}
}
/**
 * 点击修改或删除按钮事件
 * @param type 点击弹窗的类型
 * @param value 表格行数据
 */
const update = async (type: string | number, value?: any) => {
  if (type === 1) {
    popupTitle.value = '新增'
    visible.value = true
  } else {
    popupTitle.value = '修改'
    await serviceDetailFc(value.id)
    visible.value = true
    serviceItemId.value = value.id
  }
}
/**
 * 删除数据
 */
const datele = async (id: string | number) => {
  // 删除
  const res = await deleteServiceDetail(id)
  if (res.success == true) {
    Message.success('删除成功')
    getServiceItemFc()
  } else {
    Message.success('删除失败')
  }
}

/**
 * 分页网络请求
 */
const handlePageChange = (newPage: number) => {
  page.current = newPage
  getServiceItemFc()
}
/**
 * 切换显示条数事件
 */
const handlePageSizeChange = (newSize: number) => {
  page.pageSize = newSize
  page.current = 1 // 切换每页条数后重置到第一页
  getServiceItemFc()
}
/**
 * 获取表格数据
 */
const getServiceItemFc = async () => {
  const res = await serviceItem({
    page: page.current,
    size: page.pageSize
  })
  data.value = res.data.list
  page.total = res.data.total
}
/**
 * 获取厂区列表
 */
const factoryFc = async () => {
  const res = await factory()
  const newData = res.data.map((item) => ({
    value: item.id,
    label: item.name
  }))
  options.value = newData
}
/**
 * 获取详情
 */
const serviceDetailFc = async (id: number | string) => {
  const res = await getgetserviceDetail(id)
  form.value = res.data
}

/**
 * 选择框确认事件
 * @param item 当前选择对象
 */
const selectChange = (value) => {
  const label = options.value.find((item) => item.value === value)?.label || ''
  form.value.factoryName = label
}
/**
 * 服务项目管理模糊查询
 */
const fuzzySearchFc = async () => {
  const res = await fuzzySearch({
    page: page.current,
    size: page.pageSize,
    keywords: fuzzySearchValue.value
  })
  console.log(res)
  data.value = res.data.list
  page.total = res.data.total
}
/**
 * 清除按钮事件
 */
const fuzzySearchClearFc = () => {
  getServiceItemFc()
}

// 负责人选人相关变量重命名
const showUserModal = ref(false)
const userTreeData = ref<PrincipalTreeNode[]>([])
const userSearchKeyword = ref('')
const userSearching = ref(false)
const isUserSearching = ref(false)
const userSearchResults = ref<PrincipalTreeNode[]>([])
const selectedUserKeys = ref<string[]>([])

// 负责人树数据格式化
interface PrincipalTreeNode {
  title: string
  key: string
  value: string
  selectable: boolean
  disabled: boolean
  children?: PrincipalTreeNode[]
  avatar?: string
  type: string
}
const transformTreeData = (data: any[]): PrincipalTreeNode[] => {
  return data.map((node) => ({
    title: node.name,
    key: node.type === 'user' ? node.userid : node.id?.toString(),
    value: node.type === 'user' ? node.userid : node.id?.toString(),
    selectable: true,
    disabled: node.type === 'department',
    children: node.children && node.children.length > 0 ? transformTreeData(node.children) : [],
    avatar: node.avatar || '',
    type: node.type
  }))
}

const fetchUserTree = async () => {
  try {
    const rawData = await getUserTree()
    userTreeData.value = transformTreeData(rawData)
  } catch (e) {
    Message.error('获取组织架构失败')
  }
}

const showTemplateUpload = ref(false)
const templateFileList = ref<any[]>([])
const templateUploading = ref(false)
const recentTemplateUploads = ref<{ name: string, time: string, status: 'success' | 'failed' }[]>([])

const handleTemplateUpload = (options: any) => {
  let file = options.file
  if (file && file.originFileObj) {
    file = file.originFileObj
  }
  console.log('handleTemplateUpload file:', file)
  console.log('handleTemplateUpload file instanceof File:', file instanceof File)
  console.log('handleTemplateUpload file.name:', file?.name, 'size:', file?.size, 'type:', file?.type)
  templateFileList.value = [file]
}

const submitTemplateUpload = async () => {
  if (!templateFileList.value.length) return
  const fileItem = templateFileList.value[0]
  const file = fileItem.originFileObj || fileItem.file || fileItem
  console.log('submitTemplateUpload file:', file)
  console.log('submitTemplateUpload file instanceof File:', file instanceof File)
  console.log('submitTemplateUpload file.name:', file?.name, 'size:', file?.size, 'type:', file?.type)
  // 校验
  const allowedTypes = [
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'application/vnd.ms-excel'
  ]
  const fileName = file.name || ''
  const isExcelType = allowedTypes.includes(file.type)
  const isExcelExt = fileName.endsWith('.xls') || fileName.endsWith('.xlsx')
  if (!isExcelType && !isExcelExt) {
    Message.error('请上传Excel文件（.xlsx或.xls格式）')
    return
  }
  if (file.size > 10 * 1024 * 1024) {
    Message.error('文件大小不能超过10MB')
    return
  }
  templateUploading.value = true
  try {
    const formData = new FormData()
    formData.append('file', file)
    const res = await uploadTemplate(formData)
    if (res.success) {
      Message.success('上传成功')
      // showTemplateUpload.value = false // 不自动关闭弹窗
      recentTemplateUploads.value.unshift({
        name: file.name,
        time: new Date().toLocaleString(),
        status: 'success'
      })
      if (recentTemplateUploads.value.length > 5) {
        recentTemplateUploads.value = recentTemplateUploads.value.slice(0, 5)
      }
      templateFileList.value = []
    } else {
      Message.error(res.msg || '上传失败')
      recentTemplateUploads.value.unshift({
        name: file.name,
        time: new Date().toLocaleString(),
        status: 'failed'
      })
      if (recentTemplateUploads.value.length > 5) {
        recentTemplateUploads.value = recentTemplateUploads.value.slice(0, 5)
      }
    }
  } catch (e) {
    Message.error('上传失败，请重试')
    recentTemplateUploads.value.unshift({
      name: file.name,
      time: new Date().toLocaleString(),
      status: 'failed'
    })
    if (recentTemplateUploads.value.length > 5) {
      recentTemplateUploads.value = recentTemplateUploads.value.slice(0, 5)
    }
  } finally {
    templateUploading.value = false
  }
}

const handleTemplateUploadCancel = () => {
  showTemplateUpload.value = false
  templateFileList.value = []
}

onMounted(() => {
  getServiceItemFc()
  factoryFc()
  fetchUserTree()
})

const handleUserSearch = debounce(async (value: string) => {
  if (!value) {
    isUserSearching.value = false
    userSearchResults.value = []
    userSearching.value = false
    return
  }
  userSearching.value = true
  try {
    const res = await searchTree(value)
    if (res.code === '0' && res.success) {
      userSearchResults.value = transformTreeData(res.data)
      isUserSearching.value = true
    } else {
      Message.error(res.msg || '搜索失败')
    }
  } catch (e) {
    Message.error('搜索失败')
  } finally {
    userSearching.value = false
  }
}, 300)

const onUserNodeSelect = (selectedKeys: (string | number)[], data: { selected?: boolean, selectedNodes: any[], node?: any }) => {
  if (data.node && data.node.type === 'user') {
    selectedUserKeys.value = [data.node.key]
  }
}
const onUserRadioChange = (key: string) => {
  selectedUserKeys.value = [key]
}
const handleUserConfirm = () => {
  if (selectedUserKeys.value && selectedUserKeys.value.length > 0) {
    // 从搜索结果或树形数据中找到用户信息
    const findUser = (tree: PrincipalTreeNode[], key: string): PrincipalTreeNode | null => {
      for (const node of tree) {
        if (node.key === key) return node
        if (node.children) {
          const found = findUser(node.children, key)
          if (found) return found
        }
      }
      return null
    }
    const userInfo = isUserSearching.value
      ? userSearchResults.value.find((item: PrincipalTreeNode) => item.key === selectedUserKeys.value[0])
      : findUser(userTreeData.value, selectedUserKeys.value[0])
    if (userInfo) {
      form.value.userId = userInfo.key // 传参用
      form.value.userName = userInfo.title // 传参用
    }
  }
  showUserModal.value = false
}
const removeUserSelect = () => {
  form.value.userId = ''
  form.value.userName = ''
  selectedUserKeys.value = []
}
</script>

<style>
</style>
